package com.ruoyi.system.controlle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.FlowChartService;
import com.ruoyi.system.service.PersonnelInformationUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ClassUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 *描述 ：预案流程图
 *@author senyuan.li
 *@date 19:23 2024/3/31
 *@param 
 *@return 
 **/
@Controller
@RequestMapping("/flowChart")
public class FlowChartController extends BaseController
{

    @Autowired
    private FlowChartService flowChartService;


  /**
   *描述 ：流程图前
   *@author senyuan.li
   *@date 21:13 2024/4/8
   *@param [flowchart]
   *@return com.ruoyi.common.core.page.TableDataInfo
   **/
    @PostMapping("/listFront")
    @ResponseBody
    public TableDataInfo list(@RequestBody FlowChartMenus flowchart)
    {
        startPage(flowchart.getPageNum(),flowchart.getPageSize());
        List<FlowChart> list = flowChartService.selectFileDataList(flowchart);
        return getDataTable(list);
    }
  /**
   *描述 ：流程图后
   *@author senyuan.li
   *@date 21:13 2024/4/8
   *@param [flowchart]
   *@return com.ruoyi.common.core.page.TableDataInfo
   **/
    @PostMapping("/listAfter")
    @ResponseBody
    public TableDataInfo listAfter(@RequestBody FlowChartMenus flowchart)
    {
        startPage(flowchart.getPageNum(),flowchart.getPageSize());
        List<FlowChart> list = flowChartService.selectlistAfterList(flowchart);
        return getDataTable(list);
    }



    @PostMapping("/add")
    @ResponseBody
    public Map addSave(@RequestBody FlowChart flowchart)
    {

        flowchart.setCreateTime(new Date());
        flowchart.setSpare("前");
        int i = flowChartService.insertFileData(flowchart);
        Integer id = flowchart.getId();
        Map map=new HashMap();
        map.put("id",id);
        map.put("success","成功");
        return map;

    }

    /**
     *描述 ：流程图画一半，暂存起来
     *@author senyuan.li
     *@date 19:25 2024/4/22
     *@param [flowchart]
     *@return java.util.Map
     **/
    @PostMapping("/addTemporaryStorage")
    @ResponseBody
    public Map addTemporaryStorage(@RequestBody FlowChart flowchart)
    {

        flowchart.setCreateTime(new Date());
        flowchart.setSpare("暂存");
        int i = flowChartService.insertFileData(flowchart);
        Integer id = flowchart.getId();
        Map map=new HashMap();
        map.put("id",id);
        map.put("success","成功");
        return map;

    }

    /**
     *描述 ：暂存列表
     *@author senyuan.li
     *@date 19:27 2024/4/22
     *@param [flowchart]
     *@return listTemporaryStorage
     **/

    @PostMapping("/listTemporaryStorage")
    @ResponseBody
    public TableDataInfo listTemporaryStorage(@RequestBody FlowChartMenus flowchart)
    {
        startPage(flowchart.getPageNum(),flowchart.getPageSize());
        List<FlowChart> list = flowChartService.selectlistTemporaryStorage(flowchart);
        return getDataTable(list);
    }

    @GetMapping("/remove")
    @ResponseBody
    public AjaxResult remove( Integer id)
    {

        return toAjax(flowChartService.deleteUserByIds(id));
    }




    @PostMapping("/upload")
    @ResponseBody
    public FileData upload(MultipartFile file,Integer id) throws IOException {
        //把文件内容存储到本地磁盘
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String formattedDateTime = now.format(formatter);
        System.out.println(formattedDateTime);
        //获取文件原始的名称
        String originalFilename = file.getOriginalFilename();
        File file2 =new File("D:\\user");
//如果文件夹不存在则创建
        if  (!file2 .exists()  && !file2 .isDirectory())
        {
            System.out.println("//不存在");
            file2 .mkdir();
        }
        //file.transferTo的异常直接抛出去
        //再次存储的时候使用原来的文件名
        file.transferTo(new File("D:\\user\\"+originalFilename+formattedDateTime+".png"));
        FileData fileData=new FileData();
        fileData.setFileName(originalFilename);
        fileData.setFileUrl("D:\\user\\"+originalFilename+formattedDateTime+".png");

        flowChartService.insertFileImg("D:\\user\\"+originalFilename+formattedDateTime+".png",id);

        return fileData;
    }

    /**
     *描述 ：结束
     *@author senyuan.li
     *@date 22:20 2024/4/8
     *@param [id]
     *@return java.util.Map
     **/
    @GetMapping("/finish/{id}")
    @ResponseBody
    public Map finish(@PathVariable("id") Long id)
    {

        flowChartService.updatefinish(id);
        Map map=new HashMap();
        map.put("success","成功");
        return map;
    }
    /**
     *描述 ：流程图详情页面
     *@author senyuan.li
     *@date 18:14 2024/4/14
     *@param [id]
     *@return java.util.Map
     **/
    @GetMapping("/modalNodeData")
    @ResponseBody
    public FlowChartVm modalNodeData( Long id)
    {

        FlowChartVm flowchartVm =  flowChartService.getModalNode(id);

        return flowchartVm;
    }
    @GetMapping("/getflowChartNode")
    @ResponseBody
    public FlowChartNode getflowChartNode( int pid,String nodesId)
    {

        FlowChartNode flowchartVm =  flowChartService.getflowChartNode(pid,nodesId);

        return flowchartVm;
    }

     /*&*
      *描述 ：节点添加备注
      *@author senyuan.li
      *@date 22:23 2024/4/8
      *@param [flowchart]
      *@return java.util.Map
      **/
    @PostMapping("/addModalNode")
    @ResponseBody
    public Map addModalNode(@RequestBody FlowChartNode flowchartNode)
    {

        Date currentDate = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = format.format(currentDate);
        FlowChartNode   flowchartnodeobj= flowChartService.getNdesName(flowchartNode);
        if(flowchartnodeobj!=null){
        /*    if("标注".equals(flowchartNode.getOperationType())){
                flowchartNode.setId(flowchartnodeobj.getId());
                int i = flowChartService.updateModalNodeOperationType(flowchartNode);
            }else{*/
                flowchartNode.setId(flowchartnodeobj.getId());
                if(flowchartNode.equals("标注")){
                    flowchartNode.setOperationType("");
                }
            flowchartNode.setCrteatTime2(currentTime);
                int i = flowChartService.updateModalNode(flowchartNode);
        /*    }*/

        }else{
            if(flowchartNode.equals("标注")){
                flowchartNode.setOperationType("");
            }
            flowchartNode.setCrteatTime2(currentTime);
            int i = flowChartService.addModalNode(flowchartNode);
        }

        Map map=new HashMap();
        map.put("success","成功");
        return map;

    }
    /**
     *描述 ：添加通知人
     *@author senyuan.li
     *@date 22:00 2024/4/16
     *@param [FlowChart]
     *@return java.util.Map
     **/
    @PostMapping("/updateNotifyPerson")
    @ResponseBody
    public Map updateNotifyPerson(@RequestBody FlowChart FlowChart)
    {


        int i = flowChartService.updateNotifyPerson(FlowChart);
        Map map=new HashMap();
        map.put("success","成功");
        return map;

    }

   /**
    *描述 ：导出节点
    *@author senyuan.li
    *@date 19:20 2024/4/14
    *@param
    *@return
    **/

   @ResponseBody
   @RequestMapping(value = "/downloadFlowChartNode", method = RequestMethod.GET)
   public void downloadFlowChartNode(Long id, HttpServletResponse response) throws Exception{
       Calendar instance = Calendar.getInstance();
       HashMap<String, ByteArrayOutputStream> hashMap = new HashMap<>();
       //查询借货单数据
       String templateName = "处理流程.xls";
       StringBuilder builder = new StringBuilder();
       FlowChartVm flowchartVm =  flowChartService.getModalNode(id);
       ApplicationHome h = new ApplicationHome(getClass());
       String dirPath = h.getSource().toString();
       String fileName =templateName;
       InputStream input = ClassUtils.getDefaultClassLoader().getResourceAsStream("static/" + templateName);
       Workbook wbs =readExcelTemplate(fileName);
       Sheet sheet = wbs.getSheetAt(0);
       List<FlowChartNode> list = flowchartVm.getFlowChartNode();
       Row row = null;
       Cell cell = null;
       row = sheet.getRow(0);
       Cell valueCell1 = row.getCell(0);
       valueCell1.setCellValue(flowchartVm.getFlowChartName());
       row = sheet.getRow(1);
       cell = row.getCell(0);
       cell.setCellValue(flowchartVm.getNotifyPerson());
       /*for (FlowChartNode kitordervm2 : list) {*/
           int rowNumber=3;
           for (int i = 0; i < list.size(); i++) {
               FlowChartNode kitordervm2 = list.get(i);
               //随货单业务处理

           row = sheet.getRow(rowNumber);
           cell = row.getCell(0);
           cell.setCellValue(i+1);
           //cell.setCellValue(list.get(0).getAddressee()+" "+list.get(0).getTelephone() );
           cell = row.getCell(2);
          /* if(kitordervm2.getCrteatTime()!=null){
               cell.setCellValue(kitordervm2.getCrteatTime2()+","+kitordervm2.getNodes());
           }else{
               cell.setCellValue(kitordervm2.getNodes());

           }*/
               cell.setCellValue(kitordervm2.getCrteatTime2()+","+kitordervm2.getNodes());

           cell = row.getCell(10);
           if(kitordervm2.getPlace()!=null&&kitordervm2.getContent()!=null){
               cell.setCellValue(kitordervm2.getCrteatTime()!=null?kitordervm2.getCrteatTime():""+ kitordervm2.getPlace()+","+kitordervm2.getContent());
           }else if(kitordervm2.getPlace()!=null){
               cell.setCellValue(kitordervm2.getPlace());
           }else if(kitordervm2.getContent()!=null){
               cell.setCellValue(kitordervm2.getContent());
           }
               rowNumber++;
           }
           // sheet.addMergedRegion(cra);
           CellStyle style = wbs.createCellStyle();
//创建字体样式
           Font font = wbs.createFont();
//true为加粗，默认为不加粗
           style.setWrapText(true);//设置自动换行
           font.setBold(true);
           font.setFontHeightInPoints((short) 10);//字号
           style.setFont(font);
           ByteArrayOutputStream baos = new ByteArrayOutputStream();
           response.setContentType(response.getContentType());
           response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
           response.setHeader("Content-Disposition", "attachment;filename=" + new String(("处理流程.xls").getBytes(), StandardCharsets.ISO_8859_1));
           wbs.write(baos);
           byte[] bytes = baos.toByteArray();
           response.setHeader("Content-Length", String.valueOf(bytes.length));
           BufferedOutputStream bos = null;
           bos = new BufferedOutputStream(response.getOutputStream());
           bos.write(bytes);
           bos.close();
           baos.close();
           wbs.close();
   }




    public static Workbook readExcelTemplate(String templateName) throws IOException, GeneralSecurityException, InvalidFormatException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
/*        String realPath = request.getSession().getServletContext().getRealPath("/");
        File file = new File(templateName);
        InputStream is = new FileInputStream(file);*/
        InputStream is = ClassUtils.getDefaultClassLoader().getResourceAsStream("static/" + templateName);

        Workbook wbs = WorkbookFactory.create(is);
        is.close();
        return wbs;
    }



}